<template>
  <div class="dashboard-container">
    <!-- 系统公告 -->
    <el-card shadow="hover" class="notice-card">
      <template #header>
        <div class="card-header">
          <span>系统公告</span>
          <!-- 只有管理员可以发布公告 -->
          <el-button 
            v-if="isAdmin()" 
            type="primary" 
            @click="handleAddNotice"
            size="small"
          >
            发布公告
          </el-button>
        </div>
      </template>
      
      <!-- 公告列表 -->
      <div v-loading="loading" class="notice-list">
        <div v-if="notices.length === 0" class="empty-notice">
          <el-empty description="暂无公告" />
        </div>
        <div v-else>
          <div v-for="notice in notices" :key="notice.id" class="notice-item">
            <div class="notice-header">
              <h4 class="notice-title">{{ notice.title }}</h4>
              <div class="notice-meta">
                <span class="notice-publisher">发布者：{{ notice.publisherName }}</span>
                <span class="notice-time">{{ formatDateTime(notice.publishTime) }}</span>
                <!-- 只有管理员可以删除公告 -->
                <el-button 
                  v-if="isAdmin()" 
                  type="danger" 
                  link 
                  size="small"
                  @click="handleDeleteNotice(notice)"
                >
                  删除
                </el-button>
              </div>
            </div>
            <div class="notice-content">
              {{ notice.content }}
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 发布公告对话框 -->
    <el-dialog
      v-model="noticeDialog.visible"
      title="发布公告"
      width="600px"
      @close="resetNoticeForm"
    >
      <el-form
        ref="noticeFormRef"
        :model="noticeForm"
        :rules="noticeRules"
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input 
            v-model="noticeForm.title" 
            placeholder="请输入公告标题"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="noticeForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入公告内容"
            maxlength="2000"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="noticeDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveNotice" :loading="noticeDialog.loading">
            发布
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 我的借阅记录弹窗，仅普通用户 -->
    <el-dialog
      v-model="myBorrowsDialog.visible"
      title="我的借阅记录"
      width="80%"
      @close="myBorrowsDialog.visible = false"
    >
      <el-table
        :data="myBorrowsList"
        v-loading="myBorrowsDialog.loading"
        style="width: 100%"
        border
      >
        <el-table-column prop="isbn" label="ISBN" width="150" />
        <el-table-column prop="title" label="图书名称" min-width="200" />
        <el-table-column prop="author" label="作者" width="120" />
        <el-table-column prop="borrowDate" label="借阅日期" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.borrowDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="returnDate" label="应还日期" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.returnDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="actualReturnDate" label="实际归还日期" width="160">
          <template #default="{ row }">
            {{ row.actualReturnDate ? formatDateTime(row.actualReturnDate) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" width="150" show-overflow-tooltip />
      </el-table>
      <div class="pagination" style="margin-top: 20px; text-align: center;">
        <el-pagination
          v-model:current-page="myBorrowsPagination.current"
          v-model:page-size="myBorrowsPagination.size"
          :page-sizes="[5, 10, 20, 50]"
          :total="myBorrowsPagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleMyBorrowsSizeChange"
          @current-change="handleMyBorrowsCurrentChange"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getActiveNotices, publishNotice, deleteNotice } from '@/api/notice'
import { useUserStore } from '@/store/user'
import { getBorrowByUserId } from '@/api/borrow'

const userStore = useUserStore()
const currentUser = computed(() => userStore.userInfo || null)

// 判断是否为管理员
const isAdmin = () => {
  return userStore.isAdmin()
}

// 公告列表
const notices = ref([])
const loading = ref(false)

// 公告对话框
const noticeDialog = reactive({
  visible: false,
  loading: false
})

const noticeForm = reactive({
  title: '',
  content: ''
})

const noticeRules = {
  title: [
    { required: true, message: '请输入公告标题', trigger: 'blur' },
    { min: 1, max: 200, message: '标题长度在1到200个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入公告内容', trigger: 'blur' },
    { min: 1, max: 2000, message: '内容长度在1到2000个字符', trigger: 'blur' }
  ]
}

const noticeFormRef = ref()

// 获取公告列表
const fetchNotices = async () => {
  loading.value = true
  try {
    const response = await getActiveNotices(10) // 获取10条公告
    if (response.code === 200) {
      notices.value = response.data
    } else {
      ElMessage.error(response.message || '获取公告列表失败')
    }
  } catch (error) {
    console.error('获取公告列表失败:', error)
    ElMessage.error('获取公告列表失败')
  } finally {
    loading.value = false
  }
}

// 添加公告
const handleAddNotice = () => {
  noticeDialog.visible = true
  resetNoticeForm()
}

// 保存公告
const handleSaveNotice = async () => {
  if (!noticeFormRef.value) return
  
  try {
    await noticeFormRef.value.validate()
  } catch (error) {
    return
  }
  
  noticeDialog.loading = true
  try {
    const data = {
      title: noticeForm.title,
      content: noticeForm.content,
      publisherId: userStore.userInfo.id,
      publisherName: userStore.userInfo.realName || userStore.userInfo.username
    }
    
    const response = await publishNotice(data)
    if (response.code === 200) {
      ElMessage.success('发布公告成功')
      noticeDialog.visible = false
      fetchNotices() // 刷新公告列表
    } else {
      ElMessage.error(response.message || '发布公告失败')
    }
  } catch (error) {
    console.error('发布公告失败:', error)
    ElMessage.error('发布公告失败')
  } finally {
    noticeDialog.loading = false
  }
}

// 删除公告
const handleDeleteNotice = (notice) => {
  ElMessageBox.confirm(
    `确定要删除公告"${notice.title}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await deleteNotice(notice.id)
      if (response.code === 200) {
        ElMessage.success('删除公告成功')
        fetchNotices() // 刷新公告列表
      } else {
        ElMessage.error(response.message || '删除公告失败')
      }
    } catch (error) {
      console.error('删除公告失败:', error)
      ElMessage.error('删除公告失败')
    }
  })
}

// 重置公告表单
const resetNoticeForm = () => {
  Object.assign(noticeForm, {
    title: '',
    content: ''
  })
  if (noticeFormRef.value) {
    noticeFormRef.value.resetFields()
  }
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

const myBorrowsDialog = reactive({
  visible: false,
  loading: false
})
const myBorrowsList = ref([])
const myBorrowsPagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 获取我的借阅记录
const fetchMyBorrows = async () => {
  if (!currentUser.value || !currentUser.value.id) return
  myBorrowsDialog.loading = true
  try {
    const params = {
      page: myBorrowsPagination.current,
      size: myBorrowsPagination.size
    }
    const response = await getBorrowByUserId(currentUser.value.id, params)
    if (response.code === 200) {
      myBorrowsList.value = response.data.records
      myBorrowsPagination.total = response.data.total
    } else {
      ElMessage.error(response.message || '获取借阅记录失败')
    }
  } catch (error) {
    ElMessage.error('获取借阅记录失败')
  } finally {
    myBorrowsDialog.loading = false
  }
}

const handleMyBorrowsSizeChange = (size) => {
  myBorrowsPagination.size = size
  myBorrowsPagination.current = 1
  fetchMyBorrows()
}
const handleMyBorrowsCurrentChange = (current) => {
  myBorrowsPagination.current = current
  fetchMyBorrows()
}

// 自动弹窗逻辑：只要首页挂载且当前用户为普通用户就弹窗
onMounted(() => {
  fetchNotices()
  if (currentUser.value && !isAdmin()) {
    myBorrowsDialog.visible = true
    myBorrowsPagination.current = 1
    fetchMyBorrows()
  }
})

const getStatusType = (status) => {
  const statusMap = {
    1: 'success', // 借阅中
    2: 'info',    // 已归还
    3: 'warning', // 逾期
    4: 'danger'   // 丢失
  }
  return statusMap[status] || 'info'
}
const getStatusText = (status) => {
  const statusMap = {
    1: '借阅中',
    2: '已归还',
    3: '逾期',
    4: '丢失'
  }
  return statusMap[status] || '未知'
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.notice-card {
  min-height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.notice-list {
  min-height: 300px;
}

.empty-notice {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.notice-item {
  padding: 20px 0;
  border-bottom: 1px solid #ebeef5;
}

.notice-item:last-child {
  border-bottom: none;
}

.notice-header {
  margin-bottom: 15px;
}

.notice-title {
  margin: 0 0 10px 0;
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.notice-meta {
  display: flex;
  align-items: center;
  gap: 15px;
  font-size: 14px;
  color: #909399;
}

.notice-publisher {
  color: #409EFF;
  font-weight: 500;
}

.notice-time {
  color: #909399;
}

.notice-content {
  line-height: 1.6;
  color: #606266;
  font-size: 14px;
  white-space: pre-wrap;
  word-break: break-word;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 